

//".contentHolder" ".scrollbarP"
$(document).ready(function(){
    // View Message Load More
    $(".scrollbarP").bind('scroll', function(){
	if ($(this).scrollTop()==0) {
	    
	}
    });
    // Hovering Message Inbox
    $("body").on("mouseenter",".viewMsg",function(){
	if (!$(this).hasClass("active_vMsg")) {
	    $(this).addClass("loadMsgList_hover");
	}
    });
    $("body").on("mouseleave",".viewMsg",function(){
	$(this).removeClass("loadMsgList_hover");
    });
    
    // Delete Message
    $("body").on("click",".deleteMessage",function(){
	var dataID = $(this).attr("data-id");
	if (dataID=="") {
	    showNotification({
		message: "Please choose a conversation before this.",
		type: "error",
		autoClose: true,
		duration: 3
	    });
	}else{
	    var action = "deleteMessage";
	    $("body").scrollTop(0);
	    con = "Are you sure do you want to delete this?";
	   var newConfirm = new jConfirm(con, 'Confirmation Dialog','', '', '', function(r){
		if(r==true){
		    $.ajax({
			type	:	"POST",
			url		:	"/ajax/message",
			data	:	{action:action,dataID:dataID},
			cache	:	false,
			success	:	function(data){
			    if (data=="Selected message was successfully deleted.") {
				showNotification({
				    message: "Selected message was successfully deleted.",
				    type: "success",
				    autoClose: true,
				    duration: 3
				});
				$("#msg_" + dataID).animate({ backgroundColor: "whiteSmoke" }, "fast")
				.animate({ opacity: "hide" }, "slow");
			    }
			}
		    });
		}
		
	    });
	    newConfirm.themeConfirm("confirm2", {'icon':'<i class="fa fa-exclamation-triangle fl-margin-right" style="color:#f00; font-size:15px;"></i>'});	
	}
    });
    
    // Add People Conversation
    $("body").on("click",".addPeopleConversation",function(){
	var trigger = "addlistRecipient";
	
	var dataID = $(this).attr("data-id");
	var recipient = $(this).attr("data-re");
	var recipient_name = $(this).attr("data-name");
	if (dataID=="") {
	    showNotification({
		message: "Please choose a conversation before this.",
		type: "error",
		autoClose: true,
		duration: 3
	    });
	}else{
		var data_recipient = $( "body" ).data( dataID );
		var rec = "";
		$.each(data_recipient,function(id,val){
			rec += '<div class="recipient ' + trigger + ' display" id="' + trigger + '_' + id + '" data-id="' + id + '">';
				rec += '<span style="margin-right:5px;">' + val + '</span>';
				rec += '<icon class="cursor removeTag_' + trigger + '_" data-id="' + id + '">X</icon>';
			rec += '</div>';
		});
		
		var people = '<h3><i class="icon-user"></i> Add User</h3>'+
			     '<div class="hr"></div>'+
			     '<div style="overflow:auto;height:260px;padding: 5px;">'+
				'<div id="userList" style="float: left;border: 1px solid #ddd;min-height: 40px;margin-top: 5px;width: 100%;padding-bottom: 8px;">'+
				   '<div style="float:left;margin-top: 13px;margin-left:12px;font-weight: bold;">'+
				      'Users:'+
				   '</div>'+
					rec +
				      '<input type="text" id="addlistRecipient" class="input-small msgBoxTo" data-tag-id="' + recipient + '" style="border: none;box-shadow:none;margin-left: 12px;margin-top: 8px;">'+
				'</div>'+
				'<div style="float: left;width: 100%;min-height:200px;border-bottom:1px solid #ddd;"><div id="addldisplayUser"></div></div>'+
			     '</div>'+
				'<input type="button" class="btn-basicBtn pull-right" id="popup_cancel" value="Cancel"  style="margin-top:10px; margin-bottom:5px;">'+
				'<input type="button" class="btn-blueBtn pull-right addPeople" value="Add People" data-id="' + dataID + '" style="margin-top:10px;margin-right:5px;margin-bottom:5px;">';
				
			     
		
		jDialog(people, '', '', '370', '', function(){});
		$("#" + trigger).autoComplete({
			table_search: "tbuser",
			search_type:"users",
			event:"#" + trigger,
			display:"#addldisplayUser",
			allow_select: true,
			allow_delete: true
		});
			// Save Person Now
			$("body").on("click",".addPeople",function(){
				var dataID = $(this).attr("data-id");
				var action = "addPeople";
				var people = $("#addlistRecipient")[0].attributes[3].nodeValue;
				if(people=="0"){
					showNotification({
					    message: "Please choose atleast one user.",
					    type: "error",
					    autoClose: true,
					    duration: 3
					});
					$("#addlistRecipient").focus();
				}else{
					$.ajax({
						type	:	"POST",
						url	:	"/ajax/message",
						cache	:	false,
						data	:	{action:action,people:people,dataID:dataID},
						success	:	function(e){
							if (e=="Successfully added.") {
								showNotification({
									message: "User was successfully added.",
									type: "success",
									autoClose: true,
									duration: 3
								});
								
								$(".active_vMsg").trigger('click');
								$("#popup_cancel").trigger('click');
							}
						}
					});
				}
			});
	}
    });
    
    message.cNewMsg();
    message.newMsg();
    var pathname = window.location.pathname;
    var user_view = $("#user_url_view").val();
	if (pathname=="/message" || pathname== user_view + "messages") {
	    message.loadMsg();
	}	
    message.viewMsg(".viewMsg");
    message.replyMsg_conversation();
    message.load_more_msg();
    message.loadNewMsg();
    jQuery.fn.extend({
	 autoComplete: function (options) {
	 
	    var settings = {
	       table_search : "",
	       search_type : "",
	       event : "",
	       display : "",
	       allow_select : "",
	       allow_delete : ""
	    }
	    options = $.extend(settings, options);
	       var o = options;
	       var ret = "";
	       $(o.event).focus();
	       switch (o.search_type) {
		  case "users":
		     ret += "Name only";
		     break;
		  
		  case "position":
		     ret += "Position Only";
		     break;
		  
		  case "department":
		     ret += "Department Only";
		     break;
	       }
	 
	       
	       $(o.event).keyup(function(e){
		     var searchbox = $(this).val();
		     var listID = $(this).attr("data-tag-id");
		     var event = o.event.replace("#","").replace(".","");
		     var dataString = 'action=getUsers'  + '&searchword=' + searchbox + '&listID=' + listID + '&table=' + o.table_search +
		     '&search_type=' + o.search_type + '&event=' + event;
		     var M = "";
		     
		     if(searchbox==''){
			$(o.display).hide();
			
		     }else if(e.keyCode!="40" && e.keyCode !="38"){
			   $.ajax({
			      type: "POST",
			      url: "/ajax/message",
			      data: dataString,
			      dataType: 'json',
			      cache: false,
			      success: function(data){
				if (data==null) {
				    //code
				}else{
				    for (var a=0;a<data.length;a++) {
					var users = data[a];
					M += contacts(users,event);
					$(o.display).html(M).show();
					$('.add_' + event).eq(0).addClass('activeS');
					
				    }
				}
				hideRemoving();
				 //$(o.display).html(html).show();
				 //$('.add_' + event).eq(0).addClass('activeS');     
			      }
			   });	
		     }
			return false;   
	       });
	    // Allow Select on showing list  
	       switch (o.allow_select) {
		  case true:
		     var event = o.event.replace("#","").replace(".","");
		     $("body").on("click","#search_info_" + event,function(){
			var dataID = $(this).attr("data-id");
			$div = $('.add_' + event);
			var name = $("#search_name_" + dataID).attr("data-name");
			
			   addUserTag(name,dataID,o)
			   $div.eq(0).removeClass("activeS"); // remove active user selected on the search
			   showRemoving();
		     });
		  //
		    $("body").on("keydown",o.event,function(e) {
			var event = o.event.replace("#","").replace(".","");
			
			var $hlight = $('.activeS'), $div = $('.add_' + event);
			var queryReturn = parseInt($("#displayUser").attr("data-query")) + 1;
					    
			// Down
			if(e.keyCode == 40) {
			    $hlight.removeClass('activeS').next().addClass('activeS');
			    if ($hlight.next().length == 0) {
				$div.eq(0).addClass('activeS') // remove active user selected on the search
			    }
			    
			}
			// Up
			if(e.keyCode == 38) {
			    $hlight.removeClass('activeS').prev().addClass('activeS');
			    if ($hlight.prev().length == 0) {
				$div.eq(-1).addClass('activeS')
			    }
			       
			}
					    
			// Enter
			if(e.keyCode == 13) {
			   dataID = $hlight.attr("data-id"); // user ID
			   name = $("#search_name_" + dataID).attr("data-name"); // get name of the selected user
			   
			    addUserTag(name,dataID,o);
			    $div.eq(0).removeClass("activeS"); // remove active user selected on the search
			    showRemoving()
			}
		     });
		     break;
	       }
	    
	    // Allow delete for the selected tag
	       switch (o.allow_delete) {
		  case true:
		     //
		     var event = o.event.replace("#","").replace(".","");
		     $("body").on("click",".removeTag_" + event,function(){
			var dataID = $(this).attr("data-id");
			var event = o.event.replace("#","").replace(".","");
			   $("#" + event + "_" + dataID).remove();
			   getTagID(o);
		     });
		     // Escape
			$("body").on("keydown",o.event,function(e){
			    to = $(this).val();
			    if(to==""){
				// Escape
				    if(e.keyCode === 8){
					
					a = parseInt($("." + event).length) - 1;
					if (!$("." + event).eq(a).hasClass("display")) {
						$("." + event).eq(a).remove();
					}
				       
					// get all selected user id
					getTagID(o);
					$(".add_" + event).eq(0).removeClass("activeS");
					
				    }  
			    }
			});  
		     break;
	       }
	 }
     });
      
      
    $("#listRecipient1").autoComplete({
       table_search: "tbuser",
       search_type:"users",
       event:"#listRecipient1",
       display:"#displayUser1",
       allow_select: true,
       allow_delete: true
    });
    
    jQuery(function($){
      $("#searchbox").Watermark("Search");
    });
});